package com.kaguya.vams.common.exception;

import com.kaguya.vams.common.constant.HttpStatus;
import com.kaguya.vams.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * @author : kaguya
 * @date : 14:29 2021/7/29
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e){
        log.error("运行时异常--------------"+e.getMessage());
        return Result.msg(HttpStatus.FAIL.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e){
        log.error("Assert异常--------------"+e.getMessage());
        return Result.fail(HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e){

        BindingResult result = e.getBindingResult();
        result.getAllErrors().stream().findFirst().get();

        log.error("实体数据校验异常--------------"+e.getMessage());
        return Result.fail(HttpStatus.BAD_REQUEST);
    }

}
